package com.example.chapter.controller;

import com.example.chapter.entity.User;
import com.example.chapter.service.LoginService;
import com.example.chapter.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Controller
public class UserController {
//    //打开主页
//    @RequestMapping(value = "/index")
//    public String index(){
//        log.info("打开主页");
//        return "forward:index.html";
//    }
//    //打开登陆界面
//    @RequestMapping(value = "/login")
//    public String login(){
//        log.info("打开登陆界面");
//        return "forward:login.html";
//    }
//
//    //登陆验证
//    @Autowired
//    private LoginService loginService;
//    @RequestMapping(value = "/userLogin")
//    public String userLogin(String username,String password){
//        if (loginService.login(username,password)){
//            return "forward:index.html";
//        }else {
//            return "forward:login.html";
//        }
//    }
    //处理访问登陆页面的请求
@RequestMapping(value = {"/index","/main"})
public String index(){
    log.info("打开主页");
    return "index";
}
    //打开登陆界面
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView login(ModelAndView mv){
        log.info("打开登陆界面");
        mv.setViewName("login");
        return mv;
    }

    //登陆验证
    @Autowired
    private LoginService loginService;
    @RequestMapping(value = "/login",params = {"username","password"},name = "登陆验证",method = RequestMethod.POST)
//    @ResponseBody
    public ModelAndView userlogin(ModelAndView mv,User user){
        log.info(":"+user);
        if (loginService.login(user.getUsername(), user.getPassword())){
            mv.setViewName("index");
            mv.addObject("users",user);
        }else {
            mv.setViewName("login");
            mv.addObject("error","登陆失败");
        }
        return mv;
    }
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView){
//        ModelAndView modelAndView = new ModelAndView();
//        设置访问的界面
        modelAndView.setViewName("register");
        //设置数据
        modelAndView.addObject("user", new User());
        return modelAndView;
    }
    //处理注册数据
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView modelAndView,User user){
        try {
            userService.register(user);
            modelAndView.addObject("success","注册成功");
        } catch (Exception e) {
            modelAndView.addObject("error","注册失败");
            log.error(e.getMessage());
        }
        return modelAndView;
    }
}
